package com.ipc.app.dal.dao.impl;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ipc.app.dal.dao.OrderDAO;
import com.ipc.app.dal.doObject.InformationDO;
import com.ipc.app.dal.doObject.OrderDO;

/**
 * @author 雪
 * 
 */
public class OrderDAOImpl extends HibernateDaoSupport implements OrderDAO {

	public void createOrder(OrderDO orderDO) {
		this.getHibernateTemplate().save(orderDO);
	}

	public OrderDO getOrder(String orderID) {
		OrderDO orderDO = (OrderDO) this.getHibernateTemplate().get(
				OrderDO.class, orderID);
		return orderDO;
	}

	public OrderDO getOrderAndLock(String orderID) {
		OrderDO orderDO = (OrderDO) this.getHibernateTemplate().get(
				OrderDO.class, orderID, LockMode.UPGRADE);
		return orderDO;
	}

	public void updateOrder(OrderDO orderDO) {
		this.getHibernateTemplate().clear();
		this.getHibernateTemplate().update(orderDO);
	}

	@SuppressWarnings("unchecked")
	public List<OrderDO> getOrderByUser(final String userID, final int pageNumber,
			final int pageIndex) {
		List<OrderDO> orderDOs = (List<OrderDO>) this
		.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session
						.getNamedQuery("getOrderByUserID");
				query.setParameter("userId", userID);
				query.setFirstResult(pageNumber * (pageIndex - 1));
				query.setMaxResults(pageNumber);
				List<InformationDO> informationDOs = query.list();
				return informationDOs;
			}
		});
		return orderDOs;
	}
	
	@SuppressWarnings("unchecked")
	public List<OrderDO> getExpiredOrder(Date date) {
		List<OrderDO> orderDOs = this.getHibernateTemplate().findByNamedQuery(
				"queryNotPaidOrder", date);
		return orderDOs;
	}

	public int getOrderCountByUser(final String userID) {
		Integer totalOrder = (Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session
						.getNamedQuery("getOrderCountByUserID");
				query.setParameter("userId", userID);
				BigInteger count = (BigInteger) query.uniqueResult();
				return count.intValue();
			}
		});
		return totalOrder;
	}

}
